package com.example.android.apis.hardware;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;

 
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class USBio extends Activity {
	private static final String ACTION_USB_PERMISSION =   "android.permission.USB";
	private UsbManager usbmanager;
	private PendingIntent mPermissionIntent;
	private ParcelFileDescriptor filedescriptor = null;
	private FileInputStream inputstream = null;
	private FileOutputStream outputstream = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Be sure to call the super class.
        super.onCreate(savedInstanceState);
        
        /***********************USB handling******************************************/
		usbmanager = (UsbManager) getSystemService(Context.USB_SERVICE);
		mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
		filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		registerReceiver(mUsbReceiver, filter);
		ResumeAccessory();
    }

    /***********USB broadcast receiver*******************************************/
	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver(){
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)){
				synchronized (this){
					UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
					if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
						Toast.makeText(context, "Allow USB Permission", Toast.LENGTH_SHORT).show();
						OpenAccessory(accessory);
					}else {
						Toast.makeText(context, "Deny USB Permission", Toast.LENGTH_SHORT).show();
						Log.d("LED", "permission denied for accessory "+ accessory);
					}
				}
			}else if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)){
				Toast.makeText(context, "USB accessory attached", Toast.LENGTH_SHORT).show();
			}else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)){
				Toast.makeText(context, "USB accessory detached", Toast.LENGTH_SHORT).show();
			}else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)){
				Toast.makeText(context, "USB device attached", Toast.LENGTH_SHORT).show();
			}else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)){
				Toast.makeText(context, "USB device detached", Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(context, "err broadcast intent", Toast.LENGTH_SHORT).show();
			}
		}	
	};
	
	public void OpenAccessory(UsbAccessory accessory) {
		filedescriptor = usbmanager.openAccessory(accessory);
		if(filedescriptor != null){
			FileDescriptor fd = filedescriptor.getFileDescriptor();
			inputstream = new FileInputStream(fd);
			outputstream = new FileOutputStream(fd);
			byte[] buffer=new byte[100];
			try {
				outputstream.write(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/*resume accessory*/
	public int ResumeAccessory() {
		HashMap<String,UsbDevice> devices=usbmanager.getDeviceList();
		if (devices!=null) {
			Toast.makeText(this, devices.size()+" devices", Toast.LENGTH_SHORT).show();
			if (devices.size()>1) {
				UsbDevice usbDevice=devices.get(0);
				Toast.makeText(this, usbDevice.toString(), Toast.LENGTH_SHORT).show();
				UsbInterface usbInterface=usbDevice.getInterface(0);
				Toast.makeText(this, usbInterface.toString(), Toast.LENGTH_SHORT).show();
			}
		}else {
			Toast.makeText(this, "no devices", Toast.LENGTH_SHORT).show();
		}
		
		UsbAccessory[] accessories = usbmanager.getAccessoryList();
		if(accessories == null){
			Toast.makeText(this, "no accessories", Toast.LENGTH_SHORT).show();
			return 2;
		}
		Toast.makeText(this, accessories.toString(), Toast.LENGTH_SHORT).show();

		UsbAccessory accessory = (accessories.length<1 ? null : accessories[0]);
		if (accessory != null) {

			if (usbmanager.hasPermission(accessory)) {
				OpenAccessory(accessory);
			}else {
				Toast.makeText(this, "Request USB Permission", Toast.LENGTH_SHORT).show();
				usbmanager.requestPermission(accessory,
						mPermissionIntent);
			}
		}

		return 0;
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(mUsbReceiver);
		super.onDestroy();
	}

}
